package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Student;
import pojo.User;
import service.StudentService;
import service.UserService;
import util.Page;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
    @RequestMapping("/list/{currentPage}")
    public String list(Student student, @PathVariable("currentPage") Integer currentPage, Model model){
        Page page =new Page();
        int totalCount=studentService.count(student);
        page.setTotalCount(totalCount);
        page.setCurrentPage(currentPage);
        page.setTotalPage();

        int offset=(currentPage-1)*page.getPageSize();
        List<Student> students = studentService.findAll(student, offset, page.getPageSize());

        model.addAttribute("students",students);
        model.addAttribute("page",page);
        model.addAttribute("student",student);
        //打开了页面没有数据，不会自动执行该方法
        return "student/list";
    }
   @RequestMapping("/toadd")
    public String toAdd(){
        return "student/add";
    }
    @RequestMapping("/addSave")
    public String addSave(Student student){
        int result = studentService.addStudent(student);
        if(result>0) {
            return "redirect:/student/list/1";
        }
        else{
            return "student/add";
        }
    }
    @RequestMapping("/delete/{id}")
    public String deleteById(@PathVariable("id") Integer id){
        int result = studentService.deleteStudentById(id);
        if(result>0){
            return "redirect:/student/list/1";
        }else{
            return "error";
        }
    }
    @RequestMapping("/toupdate/{id}")
    public String toUpdate(@PathVariable("id") Integer id, Model model){
        Student student = studentService.findById(id);
        Date birthday = student.getBirthday();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String str_birthday = sdf.format(birthday);
        model.addAttribute("student", student);
        model.addAttribute("str_birthday", str_birthday);
        return "student/update";
    }

    @RequestMapping("/updateSave")
    public String updateSave(Student student){
        int result = studentService.updateStudent(student);
        if (result > 0) {
            return "redirect:/student/list/1";
        } else {
            return "student/update";
        }
    }
}
